﻿#include "widget.h"
#include "ui_widget.h"
#include "login.h"
#include "protocol.h"
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    client_socket = new QTcpSocket();
    client_socket->connectToHost(QHostAddress(DEFAULT_IP),DEFAULT_PORT);
    connect(client_socket,SIGNAL(readyRead()),this,SLOT(slotRecv()));
    qDebug()<<"connect "<<QHostAddress(DEFAULT_IP)<<DEFAULT_PORT;
    login_widget = new Login();
    login_widget->show();


    standItemModel = new QStandardItemModel();
    standItemModel->setColumnCount(5);
    ui->file_list_my->setEditTriggers(QAbstractItemView::NoEditTriggers);  //设置表格属性只读，不能编辑
    ui->file_list_my->setModel(standItemModel);    //挂载表格模型
    ui->file_list_my->setMouseTracking(true);
    connect(ui->file_list_my, SIGNAL(entered(QModelIndex)),this, SLOT(showToolTip(QModelIndex)));

    connect(login_widget, SIGNAL(login_clicked(QString,QString)), this, SLOT(slotLoginButClic(QString,QString)));

    layout_transfor = new QVBoxLayout;
    /* for test */
    FileDownload* f_test1 = new FileDownload;
    FileDownload* f_test2 = new FileDownload;
    layout_transfor->addWidget(f_test1);
    layout_transfor->addWidget(f_test2);
    ui->tab_transfor->setLayout(layout_transfor);



}

void Widget::slotLoginButClic(QString username, QString password)
{
    qDebug()<<username << password;
    QJsonObject json;
    json={{STR_TYPE, PROTO_TYPE_LOGIN},{STR_USER_NAME, username},  {STR_PASSWORD, password}};
    QJsonDocument doc(json);   //直接使用构造函数
    QByteArray ba = doc.toJson(QJsonDocument::Indented);

    client_socket->write(ba);
}

void Widget::sendFileRequest()
{
    QJsonObject json;
    json={
            {STR_TYPE, PROTO_TYPE_FILE_REQ},
            {STR_ID, user_id},
            {STR_PAGE, 0}
         };
    QJsonDocument doc(json);   //直接使用构造函数
    QByteArray ba = doc.toJson(QJsonDocument::Indented);

    client_socket->write(ba);
}

void Widget::slotRefreshMyFile()
{
    for (int i = 0; i < my_file_list.size(); i++)
    {

        QStandardItem *standItemFname = new QStandardItem(tr("%1").arg(my_file_list.at(i).file_name));
        QStandardItem *standItemTime = new QStandardItem(tr("%1").arg(my_file_list.at(i).upload_time));
        standItemModel->setItem(i, 0, standItemFname);
        standItemModel->setItem(i, 1, standItemTime);

        QCheckBox *update_Button = new QCheckBox;
        update_Button->setText(QStringLiteral("共享"));
        ui->file_list_my->setIndexWidget(standItemModel->index(i,2), update_Button);
        if (my_file_list.at(i).is_share)
        {
            update_Button->setChecked(1);
        }

        connect(update_Button, &QPushButton::clicked,
                        [=]()
                        {
                            my_file_list[i].is_share = update_Button->isChecked();
                            qDebug()<<my_file_list.at(i).file_id;
                            QJsonObject json;
                            json={{STR_TYPE, PROTO_TYPE_FILE_UPD},
                                  {STR_FILE_ID, my_file_list.at(i).file_id},
                                  {STR_FILE_AUTH, my_file_list.at(i).is_share}
                                 };
                            QJsonDocument doc(json);   //直接使用构造函数
                            QByteArray ba = doc.toJson(QJsonDocument::Indented);
                            client_socket->write(ba);
                        }
                       );

        QPushButton *delete_Button = new QPushButton;
        delete_Button->setText(QStringLiteral("删除"));
        ui->file_list_my->setIndexWidget(standItemModel->index(i,3),delete_Button);


        connect(delete_Button, &QPushButton::clicked,
                        [=]()
                        {
                            qDebug()<<my_file_list.at(i).file_path;
                            QJsonObject json;
                            json={{STR_TYPE, PROTO_TYPE_FILE_DEL},
                                  {STR_FILE_ID, my_file_list.at(i).file_id}};
                            QJsonDocument doc(json);   //直接使用构造函数
                            QByteArray ba = doc.toJson(QJsonDocument::Indented);
                            client_socket->write(ba);
                        }
                       );

        QPushButton *dowland_Button = new QPushButton;
        dowland_Button->setText(QStringLiteral("下载"));
        ui->file_list_my->setIndexWidget(standItemModel->index(i,4),dowland_Button);


        connect(dowland_Button, &QPushButton::clicked,
                        [=]()
                        {
                            qDebug()<<my_file_list.at(i).file_path;
                        }
                       );

    }

}


void Widget::parseFileList(QJsonObject root)
{
    int num = root[STR_NUM].toInt();
    int is_last = root[STR_IS_LAST].toInt();
    for (int i =0; i < num; i++)
    {
        QString node = QString("%1").arg(i);
        QJsonObject temp = root[node].toObject();
        ST_FILE temp_file;
        temp_file.file_name = temp[STR_FILE_NAME].toString();
        temp_file.file_path = temp[STR_FILE_PATH].toString();
        temp_file.upload_time = temp[STR_UPLOAD_TIME].toInt();
        temp_file.file_id = temp[STR_FILE_ID].toInt();
        temp_file.is_share = temp[STR_FILE_AUTH].toInt();
        qDebug()<<temp_file.file_name << temp_file.file_path << temp_file.upload_time;
        my_file_list.append(temp_file);
    }
    if (is_last)
    {
        slotRefreshMyFile();
    }
}


void Widget::slotRecv()
{
    /**解析包类型**/
    QByteArray allData = client_socket->readAll();//取出消息内容
    qDebug()<<allData;
    QString data = allData;
    //收到新数据
    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(data.toUtf8().data(), &json_error));
    if(json_error.error != QJsonParseError::NoError)
    {
        qDebug() << "json error!"<<json_error.errorString();
        return;
    }
    QJsonObject rootObj = jsonDoc.object();
    //因为是预先定义好的JSON数据格式，所以这里可以这样读取
    int type = -1;
    type = rootObj[STR_TYPE].toInt();
    qDebug()<<type;
    switch (type) {
    case PROTO_TYPE_USERINFO:    /*登录成功消息*/
        qDebug()<<rootObj[STR_ID].toInt()<<rootObj[STR_USER_NAME].toString()<<rootObj[STR_ICON].toString();
        login_widget->close();
        username = rootObj[STR_USER_NAME].toString();
        user_id = rootObj[STR_ID].toInt();
        icon = rootObj[STR_ICON].toString();
        this->show();
        sendFileRequest();  /*登录成功后请求文件列表*/
        break;

    case PROTO_TYPE_FILE_RSP:   /* 文件列表响应 */
        parseFileList(rootObj);
        break;
    default:
        break;
    }

}



Widget::~Widget()
{
    delete ui;
    client_socket->close();
}
